<template>
  <div style="display:flex;justify-content:space-between">
    <div class="left">
      <div>第一步、单击行选择商品</div>
      <ProductList key="ProductList" @listenTochildEvent="showMessageFromChild"></ProductList>
    </div>
    <div class="right">
      <div>第二步、为选中的商品设置物料及工序</div>
      <div style="padding-top:20px">
        <el-form :inline="true" :model="form" class="demo-form-inline">
          <el-form-item label="产品编号：">
            <el-input v-model="form.ProductCode" size="small" readonly="readonly"></el-input>
          </el-form-item>
          <el-form-item label="产品名称：">
            <el-input v-model="form.ProductName" size="small" readonly="readonly"></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" size="small" @click="handleSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="activeName">
        <el-tab-pane label="所需物料" name="first">
          <div>
            <el-button type="success" size="small" @click="addMetrial">批量添加物料</el-button>
            <el-button type="warning" size="small" @click="deleteData">批量删除</el-button>
          </div>
          <el-table
            :data="metrialTableData"
            border
            ref="multipleTable"
            style="width:100%;margin-top:15px"
            @selection-change="handleSelectionChange"
            :header-cell-style="style"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="MaterialCode" label="物料编号"></el-table-column>
            <el-table-column prop="MaterialName" label="物料名称"></el-table-column>
            <el-table-column prop="MaterialModel" label="型号"></el-table-column>
            <el-table-column prop="MaterialQty" label="数量">
              <template slot-scope="scope">
                <el-input type="text" v-model="scope.row.MaterialQty" />
              </template>
            </el-table-column>
            <el-table-column prop="MaterialUnit" label="单位"></el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" slot="reference" style="margin-left:10px" @click="handleDelete([scope.row.Id])">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="生产工序" name="second">
          <div>
            <el-button type="success" size="small" @click="addProcess">选择工序</el-button>
          </div>
          <el-table
            :data="processTableData"
            border
            style="width:100%;margin-top:15px"
            :header-cell-style="style"
          >
            <el-table-column prop="ProcessCode" label="工序编号"></el-table-column>
            <el-table-column prop="ProcessName" label="工序名称"></el-table-column>
            <el-table-column prop="Remark" label="备注"></el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-popconfirm
                  title="确定删除吗？"
                  @onConfirm="onConfirm(scope.row,scope.$index,processTableData)"
                >
                  <el-button type="text" size="small" slot="reference" style="margin-left:10px" @click="handleDelete2([scope.row.Id])">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <add-metrial ref="addMetrial" :styleData="style" @listenTochildEvent="addMetrialObj"></add-metrial>
    <add-process ref="addProcess" :styleData="style" @listenTochildEvent="addProcessObj"></add-process>
  </div>
</template>

<script>
import AddMetrial from './AddMetrial'
import AddProcess from './AddProcess'
import ProductList from './ProductList'
export default {
  data () {
    return {
      selectedRowKeys: [],
      loading: false,
      data: [],
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`
      },
      filters: {},
      sorter: { field: 'Id', order: 'asc' },
      formInline: {
        MaterialName: ''
      },
      form: {
        ProductCode: '',
        ProductName: '',
        ProductModel: ''
      },
      tableData: [
        {
          Code: '433',
          MaterialName: '不锈钢',
          Model: '434231',
          Spec: '565765786',
          MaterialType: '54634563'
        },
        {
          Code: '433',
          MaterialName: '不锈钢',
          Model: '434231',
          Spec: '565765786',
          MaterialType: '54634563'
        },
        {
          Code: '433',
          MaterialName: '不锈钢',
          Model: '434231',
          Spec: '565765786',
          MaterialType: '54634563'
        }
      ],
      materialData: {
        Id: '',
        ProductId: '',
        ProductCode: '',
        ProductName: '',
        MaterialId: '',
        MaterialCode: '',
        MaterialName: '',
        MaterialModel: '',
        MaterialQty: 1,
        MaterialUnit: ''
      },
      processData: {
        Id: '',
        ProductId: '',
        ProductCode: '',
        ProductName: '',
        ProcessCode: '',
        ProcessName: ''
      },
      metrialTableData: [],
      processTableData: [],
      currentRow: null,
      currentPage: 1,
      activeName: 'first',
      rowData: {},
      multipleSelection: [],
      entity: {},
      style: {
        background: '#eeeeee',
        color: '#333',
        fontWeight: 500
      }
    }
  },
  components: {
    AddMetrial,
    AddProcess,
    ProductList
  },
  methods: {
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
    },
    // 批量添加物料
    addMetrial () {
      this.$refs.addMetrial.openForm()
    },
    showMessageFromChild (data) {
      this.form.ProductName = data.ProductName
      this.form.ProductCode = data.ProductCode
      this.form.ProductModel = data.ProductModel
      this.getDataList()
      this.getDataList2()
    },
    // 删除
    onConfirm (row, index, tableData) {
      tableData.splice(index, 1)
    },
    // 批量删除
    deleteData () {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要删除的数据')
        return false
      }
      const rowkeys = []
      this.multipleSelection.forEach(item => {
        rowkeys.push(item.Id)
      })
      this.handleDelete(rowkeys)
    },
    // 添加工序
    addProcess () {
      this.$refs.addProcess.openForm()
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 子组件向父组件传递的值
    addMetrialObj (obj) {
      obj.forEach(item => {
        if (!this.isExistsMetrial(item)) {
          this.materialData.ProductId = this.form.U9ID
          this.materialData.ProductCode = this.form.ProductCode
          this.materialData.ProductName = this.form.ProductName
          this.materialData.MaterialId = this.form.Id
          this.materialData.MaterialCode = item.Code
          this.materialData.MaterialName = item.MaterialName
          this.materialData.MaterialModel = item.Model
          this.materialData.ProductModel = this.form.ProductModel
          this.materialData.MaterialQty = 1
          const formInlineTMP = Object.assign({}, this.materialData)
          this.metrialTableData.splice(this.metrialTableData.length, 1, formInlineTMP)
        }
      })
    },
    isExistsMetrial (model) {
      let result = false
      this.metrialTableData.forEach(item => {
        if (item.Id === model.Id) {
          result = true
        }
      })
      return result
    },
    addProcessObj (obj) {
      obj.forEach(item => {
        if (!this.isExistsProcess(item)) {
          this.processData.ProductId = this.form.U9ID
          this.processData.ProductCode = this.form.ProductCode
          this.processData.ProductName = this.form.ProductName
          this.processData.ProcessCode = item.ProcessCode
          this.processData.ProcessName = item.ProcessName
          const formInlineTMP = Object.assign({}, this.processData)
          this.processTableData.splice(this.processTableData.length, 1, formInlineTMP)
        }
      })
    },
    isExistsProcess (model) {
      let result = false
      this.processTableData.forEach(item => {
        if (item.ProcessCode === model.ProcessCode) {
          result = true
        }
      })
      return result
    },
    getDataList () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/Aps/Aps_ProductMaterial/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.form,
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.metrialTableData = resJson.Data
          const pagination = { ...this.pagination }
          pagination.total = resJson.Total
          this.pagination = pagination
        })
    },
    getDataList2 () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/Aps/Aps_ProductProcess/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.form,
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.processTableData = resJson.Data
          const pagination = { ...this.pagination }
          pagination.total = resJson.Total
          this.pagination = pagination
        })
    },
    handleSubmit () {
      this.confirmLoading = true
      this.entity = { ProductMaterialList: this.metrialTableData, ProductProcessList: this.processTableData }
      this.$http.post('/Aps/Aps_ProductMaterial/SaveData', this.entity).then(resJson => {
        this.confirmLoading = false

        if (resJson.Success) {
          this.$message.success('操作成功!')
          this.afterSubmit()
          this.visible = false
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    handleDelete (ids) {
      var thisObj = this

      this.$confirm({
        title: '确认删除吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            thisObj.submitDelete(ids, resolve, reject)
          }).catch(() => console.log('Oops errors!'))
        }
      })
    },
    submitDelete (ids, resolve, reject) {
      this.$http.post('/Aps/Aps_ProductMaterial/DeleteData', ids).then(resJson => {
        resolve()

        if (resJson.Success) {
          this.$message.success('操作成功!')

          this.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    handleDelete2 (ids) {
      var thisObj = this

      this.$confirm({
        title: '确认删除吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            thisObj.submitDelete2(ids, resolve, reject)
          }).catch(() => console.log('Oops errors!'))
        }
      })
    },
    submitDelete2 (ids, resolve, reject) {
      this.$http.post('/Aps/Aps_ProductProcess/DeleteData', ids).then(resJson => {
        resolve()

        if (resJson.Success) {
          this.$message.success('操作成功!')

          this.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    }
  },
  mounted () {
  }
}
</script>

<style>
.left,
.right {
  width: 49.5%;
  padding: 20px;
  background: #ffffff;
}
.el-table td,
.el-table th {
  padding: 6px 0;
}
</style>
